<template>
  <div class="dropdown">
  <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="isShowFn" ref="dropdownLink">{{ title }}</a>
  <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isShow" ref="dropdownRef">
    <slot></slot>
  </ul>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      required: true
    },
    trigger: {
      type: String,
      default: () => {
        return 'click'
      }
    }
  },
  emits: ['on-click', 'on-clickoutside'],
  setup (props, context) {
    const isShow = ref(false)
    const dropdownRef = ref<null | HTMLElement>(null)
    const dropdownLink = ref<null | HTMLElement>(null)
    const isShowFn = () => {
      isShow.value = !isShow.value
    }
    const handler = (e: MouseEvent) => {
      if (dropdownRef.value) {
        if (e.target === dropdownLink.value) {
          isShow.value = true
        } else if (dropdownRef.value.contains(e.target as HTMLElement)) {
          context.emit('on-click', (e.target as HTMLElement).innerHTML)
          isShow.value = false
        } else {
          context.emit('on-clickoutside')
          isShow.value = false
        }
      }
    }
    onMounted(() => {
      document.addEventListener('click', handler)
    })
    onUnmounted(() => {
      document.removeEventListener('click', handler)
    })
    return {
      isShow,
      isShowFn,
      dropdownRef,
      dropdownLink
    }
  }
})
</script>
